from fastapi import FastAPI, Query
from apscheduler.schedulers.asyncio import AsyncIOScheduler
"""
scheduler.start()  启动服务
scheduler.add_job  添加任务
scheduler.pause_job(task_id)  暂停任务
scheduler.resume_job(task_id)  重新启动任务
scheduler.remove_job(task_id)  删除任务

scheduler.shutdown()
scheduler.shutdown(wait=false)
"""


app = FastAPI()

scheduler = AsyncIOScheduler()
scheduler.start()


async def task_a(x):
    print(f"执行task-a: {x}")


@app.get('/demo')
async def demo_a():
    return {"ms": "demoa"}


@app.post('/task')
async def add_task_a():
    # 添加任务, 每个任务都有唯一的id
    scheduler.add_job(
        task_a, args=('hello', ), trigger='interval', id='task1', seconds=5
    )
    return {"msg": "任务创建成功！"}


@app.get('/pause')
async def pause_job_a(
        task_id: str = Query(..., title='任务id')
):
    """暂停任务"""
    scheduler.pause_job(task_id)    # task_id 参数校验，先看有没有
    return {"msg": "任务暂停！"}


@app.get('/resume')
async def resume_job_a(
        task_id: str = Query(..., title='任务id')
):
    """暂停重启"""
    scheduler.resume_job(task_id)
    return {"msg": "任务重启！"}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(
        app='fast:app',
        host="127.0.0.1",
        port=8000, reload=True
    )




